package com.ctshk.rpc.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.rpc.payment.entity.PayConfig;
import com.ctshk.rpc.payment.enums.PaymentMethod;
import com.ctshk.rpc.payment.mapper.PayConfigMapper;
import com.ctshk.rpc.payment.service.IPayConfigService;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 支付配置表 服务实现类
 * </p>
 *
 * @author hef
 * @since 2021-04-21
 */
@Service
public class PayConfigServiceImpl extends ServiceImpl<PayConfigMapper, PayConfig> implements IPayConfigService {
    @Override
    public <T> T getConfig(PaymentMethod req, Class<T> clazz) {
        PayConfig config = getOne(Wrappers.<PayConfig>lambdaQuery()
                .eq(PayConfig::getPaymentMethod, req.getType())
                .eq(PayConfig::getIsValid, true)
                .eq(PayConfig::getIsDeleted, IsDeletedCode.NO.getCode())
        );
        if (config == null || StringUtils.isBlank(config.getConfigJson())) {
            throw new BusinessException(SystemError.PAY_22000);
        }
        T t = JSON.parseObject(config.getConfigJson(), clazz);
        if (Objects.isNull(t)) {
            throw new BusinessException(SystemError.PAY_22000);
        }
        return t;
    }

    @Override
    public <T> T getConfigById(PaymentMethod req, Class<T> clazz) {
        PayConfig config = getOne(Wrappers.<PayConfig>lambdaQuery()
                .eq(PayConfig::getId, req.getCode())
                .eq(PayConfig::getIsValid, true)
                .eq(PayConfig::getIsDeleted, IsDeletedCode.NO.getCode())
        );
        if (config == null || StringUtils.isBlank(config.getConfigJson())) {
            throw new BusinessException(SystemError.PAY_22000);
        }
        T t = JSON.parseObject(config.getConfigJson(), clazz);
        if (Objects.isNull(t)) {
            throw new BusinessException(SystemError.PAY_22000);
        }
        return t;
    }
}
